#include "CPUIntensiveThread.h"
#include "WebBaseInterface.h"


void CPUIntensiveThread::SClientRequestComeCallback(uS::Async* handle)
{
	if (handle)
	{
		CPUIntensiveThread* px = (CPUIntensiveThread*)(handle->getData());
		if (px)
		{
			px->MemClientRequestComeCallback();
		}
	}
}

CPUIntensiveThread::CPUIntensiveThread(WebBaseInterface* pgw):_webGateWay(pgw)
{
	
	_cpuThreads = std::make_shared<std::thread>(&CPUIntensiveThread::CpuIntensiveProcThread, this);
}


CPUIntensiveThread::~CPUIntensiveThread()
{
}

void CPUIntensiveThread::WaitJoin()
{
	if (_cpuThreads->joinable())
	{
		_cpuThreads->join();
	}
}

void CPUIntensiveThread::CpuIntensiveProcThread()
{
	uWS::Hub hub;
	_asyncClientRequest = std::make_shared<uS::Async>(hub.getLoop());
	_asyncClientRequest->setData(this);
	_asyncClientRequest->start(&CPUIntensiveThread::SClientRequestComeCallback);
	_run = true;
	hub.run();
}

void CPUIntensiveThread::PushJsonRequestMessage(std::shared_ptr<SessionRequestMessageBody> msg)
{
	_recvJsonMessages.enqueue(msg);
	if (_run)
	{
		_asyncClientRequest->send();
	}
}

void CPUIntensiveThread::PushPBRequestMessage(std::shared_ptr<SessionRequestMessageBody> msg)
{
	_recvPBMessages.enqueue(msg);
	if (_run)
	{
		_asyncClientRequest->send();
	}
}

void CPUIntensiveThread::MemClientRequestComeCallback()
{
	
	std::shared_ptr<SessionRequestMessageBody> msg;
	bool bHasMsg = _recvJsonMessages.try_dequeue(msg);

	while (bHasMsg) //has json message
	{
		std::string str{ "hello.world" };
		_webGateWay->PushWebSocketClientResponse(ResponseType::unicast, msg->sessionid, str.c_str(), str.length());
		_webGateWay->NotifyClientResponse();
		bHasMsg = _recvJsonMessages.try_dequeue(msg);
	}
	bHasMsg = _recvPBMessages.try_dequeue(msg);
	while (bHasMsg) //has protobuf message
	{

		bHasMsg = _recvPBMessages.try_dequeue(msg);
	}
	
	
}
